# -*- coding: utf-8 -*-

import random
import os
import re
import PathConfig
import time
import string
import renameFuncName
# 替换函数名 


randomKeyList = ['top','right','bottom','left','border','padding','margin','width','height','style','solid','dashed','line','display','block','inline','text','align','list','center','auto','float','clear','both','position','absolute','relative','static','fixed','background','font','color','bold','italic','size','text','image','img','normal','repeat','decoration','indent','overflow','hidden','none','normal','radius','shadow','visited','hover','active','button','cursor','pointer','outline','value','collapse','rowspan','colspan','verticle','middle','colgroup','alert','mouse','clear','console','load','document','element','attr','hide','show','slide','toggle','true','false','current','siblings','parent','children','replace','fade','remove','add','append','prepend','after','before','set','interva','empty','animate','delay','index','page','scroll','transform','transition','translate','scale','rotate','keyframes','origin','duration','header','article','section','figure','footer','video','autoplay','controls','loop','muted','volume','disabled','max','min','datalist','option','value','is','id','with','space','path','temp','info','error','success','type','item','dic','str']

# 'source'  'link'



# 属性名 - 普通
propertyNorList = []
propertyNorList_new = []

# 属性名 - XIB
propertyXibList = []
propertyXibList_new = []

# 属性名 - XIB 中的ID OhN-5j-jiz
propertyXMLList = []
propertyXMLList_new = []

# xib路劲
xibFilePathList = []
# xib的中的ID
xibXMLIDList = []
# xib的中的destination
xibXMLDestinationList = []   


# 路径信息
pathInfoList = []

duplicateKey = []


# 过滤掉的函数名
ignoreList = [
	'currentSkin',
	'text',
	'title',
	'appMainColor',
	'name',
	'body',
	'sort',
	'content',
	'icon',
	'type',
	'count',
	'font',
	'color',
	'delegate',
	'key',
	'selected',
	'cover',
	'textColor',
	'window',
	'tag',
	'titleLabel'
	]


# 根据骆驼
def createRandomProperty(propertyName):
	# propertyName_new = PathConfig.file_pre_class_type.lower()+'_'+propertyName+'_'+(random.choice(randomKeyList))
	propertyName_old = propertyName
	propertyName_new = propertyName;

	propertyName_old = propertyName_old.decode('utf-8')
	pattern = u'([A-Z]{1}[a-z0-9]*)'
	results = re.findall(pattern,propertyName_old)

	
	if len(results) > 0:
		s = results[len(results)-1]
		name = s.encode('utf-8')

		propertyName_new = propertyName.replace(name,(random.choice(randomKeyList)).capitalize()+name)
		propertyName_new = PathConfig.file_pre_class_type.lower()+'_'+propertyName_new

	else:
	 	propertyName_new = PathConfig.file_pre_class_type.lower()+'_'+propertyName+'_'+(random.choice(randomKeyList))

	return propertyName_new


def cleanRandomProperty(propertyName):

	if propertyName.startswith(PathConfig.file_pre_class_type.lower()):

		print propertyName

		propertyName = propertyName.replace(PathConfig.file_pre_class_type.lower()+'_','')

		propertyName_clean = propertyName
		propertyName_clean = propertyName_clean.decode('utf-8')

		pattern = u'([A-Z]{1}[a-z0-9]*)'
		results = re.findall(pattern,propertyName_clean)
		if len(results) > 1:
			s = results[len(results)-2]
			name = s.encode('utf-8')

			propertyName = propertyName.replace(name,'')
			# print propertyName

		else:
			spList = propertyName.split('_')
			if len(spList) > 1:
				# 只有
				lastPath = spList[len(spList)-1]
				if len(lastPath) < 11:
					propertyName = propertyName.replace('_'+lastPath,'')
					# print propertyName

	return propertyName


def fileContentReplace(file_str,proNameOld,proNameNew):

	file_str = file_str.replace(' '+proNameOld+';',' '+proNameNew+';')
	file_str = file_str.replace(' '+proNameOld+'.',' '+proNameNew+'.')
	file_str = file_str.replace(' '+proNameOld+'[',' '+proNameNew+'[')
	file_str = file_str.replace(' '+proNameOld+']',' '+proNameNew+']')
	file_str = file_str.replace(' '+proNameOld+')',' '+proNameNew+')')
	file_str = file_str.replace(' '+proNameOld+' ',' '+proNameNew+' ')

	file_str = file_str.replace(':"'+proNameOld+'"',':"'+proNameNew+'"')
	file_str = file_str.replace('"'+proNameOld+'":','"'+proNameNew+'":')

	file_str = file_str.replace('_'+proNameOld+' ','_'+proNameNew+' ')
	file_str = file_str.replace('_'+proNameOld+'.','_'+proNameNew+'.')
	file_str = file_str.replace('_'+proNameOld+']','_'+proNameNew+']')
	file_str = file_str.replace('_'+proNameOld+';','_'+proNameNew+';')
	file_str = file_str.replace('_'+proNameOld+')','_'+proNameNew+')')

	file_str = file_str.replace('*'+proNameOld+';','*'+proNameNew+';')
	file_str = file_str.replace('*'+proNameOld+' ','*'+proNameNew+' ')
	file_str = file_str.replace('*'+proNameOld+'=','*'+proNameNew+'=')

	file_str = file_str.replace('.'+proNameOld+' ','.'+proNameNew+' ')
	file_str = file_str.replace('.'+proNameOld+'.','.'+proNameNew+'.')
	file_str = file_str.replace('.'+proNameOld+',','.'+proNameNew+',')
	file_str = file_str.replace('.'+proNameOld+')','.'+proNameNew+')')
	file_str = file_str.replace('.'+proNameOld+']','.'+proNameNew+']')
	file_str = file_str.replace('.'+proNameOld+';','.'+proNameNew+';')
	file_str = file_str.replace('.'+proNameOld+'[','.'+proNameNew+'[')
	file_str = file_str.replace('.'+proNameOld+'?','.'+proNameNew+'?')
	file_str = file_str.replace('.'+proNameOld+'}','.'+proNameNew+'}')

	file_str = file_str.replace(')'+proNameOld+' ',')'+proNameNew+' ')
	file_str = file_str.replace(')'+proNameOld+'.',')'+proNameNew+'.')
	file_str = file_str.replace(')'+proNameOld+'{',')'+proNameNew+'{')
	file_str = file_str.replace(')'+proNameOld+';',')'+proNameNew+';')
	file_str = file_str.replace(')'+proNameOld+'\n',')'+proNameNew+'\n')

	file_str = file_str.replace('('+proNameOld+' ','('+proNameNew+' ')
	file_str = file_str.replace('('+proNameOld+'.','('+proNameNew+'.')
	file_str = file_str.replace('('+proNameOld+')','('+proNameNew+')')

	file_str = file_str.replace(':'+proNameOld+']',':'+proNameNew+']')
	file_str = file_str.replace(':'+proNameOld+' ',':'+proNameNew+' ')
	file_str = file_str.replace(':'+proNameOld+'.',':'+proNameNew+'.')
	file_str = file_str.replace(':'+proNameOld+'}',':'+proNameNew+'}')

	file_str = file_str.replace(','+proNameOld+' ',','+proNameNew+' ')
	file_str = file_str.replace(','+proNameOld+'.',','+proNameNew+'.')
	file_str = file_str.replace(','+proNameOld+']',','+proNameNew+']')
	file_str = file_str.replace(','+proNameOld+')',','+proNameNew+')')

	file_str = file_str.replace('['+proNameOld+'.','['+proNameNew+'.')
	file_str = file_str.replace('['+proNameOld+' ','['+proNameNew+' ')
	file_str = file_str.replace('['+proNameOld+']','['+proNameNew+']')


	proName1 = proNameOld[0].capitalize() + proNameOld[1:len(proNameOld)]
	proName2 = proNameNew[0].capitalize() + proNameNew[1:len(proNameNew)]
	file_str = file_str.replace('set'+proName1+':','set'+proName2+':')

	# print 'set'+proName1+':' + '====>>>>' + 'set'+proName2+':'

	return file_str


# 替换XIB关联的属性 这个执行完 不替换
def replaceXibPropertyName():

	for xibPath in xibFilePathList:

		with open(xibPath) as f:
			file_str = f.read()

			# 找出ID 和 destination
			content = file_str.decode('utf-8')
			pattern_id = u'id=\"([^\"]*)\"'
			results_id = re.findall(pattern_id,content)
			for s in results_id:
				nameID = s.encode('utf-8')
				if nameID not in propertyXMLList:
					if nameID.find('-') > 1:
						propertyXMLList.append(nameID)

			pattern_destination = u'destination=\"([^\"]*)\"'
			results_destination = re.findall(pattern_destination,content)
			for s in results_destination:
				nameID = s.encode('utf-8')
				if nameID not in propertyXMLList:
					if nameID.find('-') > 1:
						propertyXMLList.append(nameID)

	# 随机生成 对应的ID
	for i in range(0,len(propertyXMLList)):

		while len(propertyXMLList_new) != len(propertyXMLList):
	 		ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 3)) + '-' + ''.join(random.sample(string.ascii_letters + string.digits, 3)) + '-' + ''.join(random.sample(string.ascii_letters + string.digits, 3))
	 		
	 		if ran_str not in propertyXMLList_new:
	 			propertyXMLList_new.append(ran_str)
			
	# print propertyXibList
	# print propertyXibList_new

	# 替换内容
	for xibPath in xibFilePathList:

		with open(xibPath) as f:
			file_str = f.read()

			# 替换XIB关联的属性		
			for i in range(0,len(propertyXibList)):

				proNameOld = propertyXibList[i]
				proNameNew = propertyXibList_new[i]

				file_str = file_str.replace('="'+proNameOld+'"','="'+proNameNew+'"')
				
				# 在普通的属性 映射中 没有添加进去
				if proNameOld not in propertyNorList:
					propertyNorList.append(proNameOld)
					propertyNorList_new.append(proNameNew)
				else:
					index = propertyNorList.index(proNameOld)
					propertyNorList_new[index] = proNameNew

			# print file_str

			# ID 替换
			for i in range(0,len(propertyXMLList)):
				proNameOld = propertyXMLList[i]
				proNameNew = propertyXMLList_new[i]

				file_str = file_str.replace('"'+proNameOld+'"','"'+proNameNew+'"')


		with open(xibPath, 'w') as f:
			f.write(file_str)

		pathList = xibPath.split('/')
		print pathList[len(pathList)-1]
	


# 替换自定义的属性
def replaceNormalPropertyName():

	
	for pathInfo in pathInfoList:
		
		tmp_path = pathInfo['path']
		filename = pathInfo['name']

		file_str = ''
		with open(tmp_path) as f:
			file_str = f.read()

			for i in range(0,len(propertyNorList)):

				proNameOld = propertyNorList[i]
				proNameNew = propertyNorList_new[i]

				file_str = fileContentReplace(file_str,proNameOld,proNameNew)

				
		with open(tmp_path, 'w') as f:
			f.write(file_str)

		print filename


# 获取所有属性信息
def getAllPropertyName(isClean = False):
	
	for pathInfo in pathInfoList:
		
		tmp_path = pathInfo['path']
		filename = pathInfo['name']

		with open(tmp_path) as f:
			file_str = f.read()				
			file_str = file_str.split('\n')
			for line in file_str:
				line = line.lstrip()
				if line.startswith('@property'):
					# 是XIB的属性类型
					isXibProperty = line.find('IBOutlet')>0

					content = line.decode('utf-8')
					pattern = u'\\w[-\\w.+]*;'
					results = re.findall(pattern,content)
					for s in results:
						propertyName = s.encode('utf-8')
						propertyName = propertyName.replace(' ','')
						propertyName = propertyName.replace(';','')
						if propertyName.startswith('_'):
							continue
						# 过滤
						if propertyName in ignoreList:
							continue

						propertyName_old = propertyName
						# 过滤裁剪一下 旧版替换
						propertyName = cleanRandomProperty(propertyName)
						
						
						# 随机数组中有已有的属性
						if propertyName in randomKeyList:
							duplicateKey.append(propertyName)


						if isXibProperty:
							if propertyName_old not in propertyXibList:

								propertyName_new = propertyName
								if not isClean:
									propertyName_new = createRandomProperty(propertyName)
									
								propertyXibList.append(propertyName_old)
								propertyXibList_new.append(propertyName_new)

						else:
							if propertyName_old not in propertyNorList:

								propertyName_new = propertyName
								if not isClean:
									propertyName_new = createRandomProperty(propertyName)

								propertyNorList.append(propertyName_old)
								propertyNorList_new.append(propertyName_new)

	# 替换XIB关联的属性		
	for i in range(0,len(propertyXibList)):

		proNameOld = propertyXibList[i]
		proNameNew = propertyXibList_new[i]

		# 在普通的属性 映射中 没有添加进去
		if proNameOld not in propertyNorList:
			propertyNorList.append(proNameOld)
			propertyNorList_new.append(proNameNew)
		else:
			index = propertyNorList.index(proNameOld)
			propertyNorList_new[index] = proNameNew
	

	# print 'propertyXibList === \n\n %s \n\n' % propertyXibList

	# print 'propertyXibList_new === \n\n %s \n\n' % propertyXibList_new

	# print 'propertyNorList === \n\n %s \n\n' % propertyNorList

	# print 'propertyNorList_new === \n\n %s \n\n' % propertyNorList_new


# 遍历所有路径
def traversePath(file_dir):
	
	fs = os.listdir(file_dir)
	for dir in fs:
		if dir.startswith('.'):
			#过滤隐藏
			continue
		

		tmp_path = os.path.join(file_dir, dir)
		if not os.path.isdir(tmp_path):

			if dir.endswith('.xib'):
				xibFilePathList.append(tmp_path)
				continue
			if not dir.endswith('.h') and not dir.endswith('.m'):
				continue
			if dir.find(PathConfig.file_pre_class_type) < 0:
				# 不是以这个开头的文件过滤掉
				if dir.find('AppDelegate') < 0:
					continue

			pathInfoList.append({'name':dir,'path':tmp_path});
			
		else:
			# 是文件夹,则递归调用
			traversePath(tmp_path)


def main():

	traversePath(PathConfig.rub_filepath)
	
	getAllPropertyName();
	# getAllPropertyName(True);
	
	if len(duplicateKey) == 0:

		print '\n\n  开始替换 函数   '
		# ignoreList = propertyNorList + propertyXibList
		# renameFuncName.beginRenameFuncName(ignoreList)

		
		print '\n\n  开始替换 属性   '
		replaceXibPropertyName()
		replaceNormalPropertyName();

		
	else:
		print '随机数组中的 %s 跟已有属性有重复 要删除' % duplicateKey

	print('Finish done')

if __name__ == '__main__':
	main()

